<template>
    <div>
        <a-card style="width: 100%" :tabList="tabList" :activeTabKey="activeTabKey"
            @tabChange="key => onTabChange(key)">
          
            <template #customTab="item">
                <!-- 通知消息-->
                <a-badge :dot="messageStore.redCount[item.index] > 0" :offset="[2, -2]">
                    {{ item.tab }} 
                </a-badge>
               
            </template>

            <template #tabBarExtraContent>
                <a-button type="default" @click="handleReadAll">
                    全部已读
                </a-button>
            </template>

            <!-- 列表数据 -->
            <a-skeleton avatar active :loading="loading" :paragraph="{ rows: 2 }">
                <a-list v-if="list.length > 0" :pagination="pagination" item-layout="horizontal" :data-source="list">
                    <template #renderItem="{ item }">
                            <a-list-item class="list-item">
                                <a-list-item-meta>
                                    <template #title>
                                        <a-space :size="5">
                                            <!-- 跳转对应的用户中心页 -->
                                            <router-link class="userName" tag="a" :to="{path:'/user/control/home',query: {userId: item.senderId}}" target="_blank">
                                                {{ item.senderUsername }}
                                            </router-link>
                                            <span class="clickable ellipsis" @click="() => handleSource(item)"
                                            v-if="activeTabKey === MessageType.LIKE_COLLECT" >
                                                {{ item.value }}
                                            </span>
                                            <span v-else @click="() => handleSource(item)" class="clickable ellipsis">回复了您</span>

                                        </a-space>
                                        <!-- <div v-if="activeTabKey === 'LIKE,COLLECT'" class="time">{{ item.createTime }}</div> -->
                                    </template>
                                    <template #avatar>
                                        <router-link tag="a" :to="{path:'/user/control/home',query: {userId: item.senderId}}" target="_blank">
                                            <a-avatar :size="60" :src="item.senderAvatar" />
                                        </router-link>                           
                                    </template>
                                    <template #description>
                                        <div>
                                            <p v-if="activeTabKey === MessageType.COMMENT" @click="() => handleSource(item)" style="color: #222;font-size: 14px; cursor: pointer;">{{
                                                item.value }}</p>
                                            <div class="time">
                                                {{ item.createTime }}
                                                <template v-if="activeTabKey === MessageType.COMMENT">
                                                    <a-button type="link" v-if="!item.likeCommentFlag"
                                                        @click="handleLike('like', item)"
                                                        :loading="loadingStates.get(item.messageId)">
                                                        <template #icon><LikeOutlined /></template>
                                                        点赞
                                                    </a-button>
                                                    <a-button type="link" v-else 
                                                        @click="handleLike('unlike', item)" 
                                                        :loading="loadingStates.get(item.messageId)"
                                                        style="color: #1677ff;">
                                                        <template #icon><LikeOutlined /></template>
                                                        已赞
                                                    </a-button>
                                                </template>
                                                <a-button type="link" class="delete-button"
                                                    :loading="loadingStates.get(item.messageId)"
                                                    @click="handleDelete(item.messageId)">
                                                    <template #icon><DeleteOutlined /></template>
                                                    删除通知
                                                </a-button>
                                            </div>
                                        </div>
                                    </template>
                                </a-list-item-meta>
                                <template #extra>
                                    <div class="postContent">{{ item.meta.content }}</div>
                                </template>
                            </a-list-item>
                    </template>
                </a-list>
                <a-empty v-else title="暂无数据" />
            </a-skeleton>

        </a-card>
    </div>
</template>

<script setup lang="ts">
import { DeleteOutlined, LikeOutlined } from '@ant-design/icons-vue';
import { pageList, readMessage, deleteMessage } from '@/api/front/message';
import { likeComment } from '@/api/front/like';
import { MessageType, MessageVO } from '@/api/front/message/types';
import useMessageStore from '@/store/modules/message';
import { ref, onBeforeUnmount } from 'vue';
import { message } from 'ant-design-vue';

const messageStore = useMessageStore();

const pagination = ref({
    onChange: (page: number) => {
        console.log(page);
        pagination.value.pageNum = page;
    },
    pageNum: 1,
    showSizeChanger: false,
    pageSize: 10,
    total: 100,
    showTotal: (total: number) => `总数 ${total}`,
});

const activeTabKey = ref(MessageType.COMMENT);
const tabList = ref([
    { key: MessageType.COMMENT, tab: '评论互动', index: 1 },
    { key: MessageType.LIKE_COLLECT, tab: '赞和收藏', index: 2 },
    // { key: '3', tab: '新增关注' },
    // { key: 'SYSTEM', tab: '系统通知' },
    // { key: '5', tab: '私信' },
]);

const list = ref<MessageVO[]>([]);
const loading = ref(false);

const loadingStates = ref(new Map<number, boolean>());

const onTabChange = async (key: MessageType) => {
    loading.value = true;
    loadingStates.value.clear();
    try {
        const res = await pageList({ pageNum: pagination.value.pageNum, pageSize: pagination.value.pageSize }, key);
        //reverse让最新的消息排在最前面
        list.value = res.data.rows.reverse();
        pagination.value.total = res.data.total;
        activeTabKey.value = key;

    } finally {

        loading.value = false;

    }
};

/**
 * 跳转对应的资源目标
 */
 const handleSource = (item: MessageVO) => {
    if (activeTabKey.value === MessageType.LIKE_COLLECT) {
        // 点赞收藏消息跳转逻辑保持不变
        if(item.meta.postsId){
            window.open(`/social/detail?postId=${item.meta.postsId}`, '_blank');
        }else{
            window.open(`/angling/detail/${item.meta.fishSiteId}`, '_blank');
        }
    } else if (activeTabKey.value === MessageType.COMMENT) {
        // 评论消息跳转逻辑修改
        const url = new URL(`${window.location.origin}/social/detail`);
        url.searchParams.set('postId', item.meta.postsId);
        url.searchParams.set('commentId', item.meta.commentId);
        
        // 如果存在父评论ID，添加parentId参数
        if (item.meta.parentId && item.meta.parentId !== '0') {
            url.searchParams.set('parentId', item.meta.parentId);
        }
        
        window.open(url.toString(), '_blank');
    }
    // 发送取消红点接口
     readMessage([item.messageId]);
};

/**
 * 全部已读
 */
const handleReadAll = async () => {
    loading.value = true;
    const ids = list.value.map(item => item.messageId);
    await readMessage(ids as number[]);
    // 重新获取数据
    onTabChange(activeTabKey.value);
    // 重新读取红点数据
    messageStore.getRedCount();
}

/**
 * 删除消息
 * @param id 消息ID
 */
const handleDelete = async (id: number) => {
    try {
        loadingStates.value.set(id, true);
        await deleteMessage([id]);
        await onTabChange(activeTabKey.value);
        messageStore.getRedCount();
    } finally {
        loadingStates.value.set(id, false);
    }
}

/**
 * 点赞
 * @param type 类型 like,unlike
 */
 const handleLike = async (type: string, item: MessageVO) => {
    try {
        loadingStates.value.set(Number(item.messageId), true);
        // 检查评论是否存在
        if (!item.meta?.commentId) {
            message.error('该评论已不存在');
            return;
        }
        const res = await likeComment({ type, commentId: item.meta.commentId });
        // 只有请求成功时才更新状态
        if (res.code === 200) {
            item.likeCommentFlag = type === 'like';
        }
    } catch {
        //在响应拦截器里处理了
    } finally {
        loadingStates.value.set(Number(item.messageId), false);
    }
}
const route = useRoute();
onMounted(() => {
    if (route.query.type) {
        activeTabKey.value = route.query.type as MessageType;
    }
    onTabChange(route.query.type ? route.query.type as MessageType : MessageType.COMMENT);
})

onBeforeUnmount(() => {
    loadingStates.value.clear();
});
</script>

<style lang="scss" scoped>
.clickable {
    cursor: pointer;
    color: #505050;
    font-size: 14px;
}

.time {
    font-size: 12px;
    color: #888;
    margin-top: 5px;
    min-height: 22px;
    display: flex;
    align-items: center;
}

:deep(.ant-btn-link) {
    color: #222;
    padding: 0;
    margin-left: 8px;
}

.delete-button {
    visibility: hidden;
    opacity: 0;
    transition: opacity 0.2s ease;
    margin-left: 8px !important;
}

.list-item{
    .userName{
        color: #2c2c2c;
        font-weight: bold;
        font-size: 16px;
    }
}

.userName:hover {
    color: #76cbef;
}
.list-item:hover .delete-button {
    visibility: visible;
    opacity: 1;
    
}

.ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 200px;
    
}

.postContent{
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    min-width: 100px;
    max-width: 00px;
    color: #999;
}
</style>